package cn.edu.scnu.rabbitmq.test;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;
import org.junit.Before;
import org.junit.Test;

public class SimpleMode {
    private Channel channel;

    @Before
    public void initChannel() throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.126.129");
        factory.setPort(5672);
        factory.setUsername("guest");
        factory.setPassword("guest");
        factory.setVirtualHost("/");
        Connection connection = factory.newConnection();
        channel = connection.createChannel();
    }

    @Test
    public void send() throws Exception {
        String message = "Hello Rabbitmq";
        String routingKey = "TestKey";
        channel.queueDeclare("TestKey", false, false, false, null);
        channel.basicPublish("", routingKey, null, message.getBytes());
    }

    @Test
    public void consumer() throws Exception {
        QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume("TestKey", consumer);
        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            System.out.println(new String(delivery.getBody()));
        }
    }
}
